package com.pf.business.upload.listener;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.google.common.collect.Lists;
import com.pf.business.upload.dto.UploadBill;
import com.pf.common.dto.ExcelErrorParam;
import com.pf.common.enums.ResultRespEnum;
import com.pf.common.exception.BusinessException;
import com.pf.utils.ValidateUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * 账单excel上传校验
 * <p>
 * isBlocked为true，表示数据校验不通过，则立即返回校验不通过的异常信息。
 * isBlocked为false，表示数据校验不通过，则继续校验下一行数据。
 * <p>
 * 将每行校验失败的信息保存在excelErrorMsgList中，校验通过的数据保存在billList
 *
 * @author PanFei
 * @version 1.0.0
 * @createTime 2023/7/16 16:14
 */
@Slf4j
public class UploadBillReadListener implements ReadListener<UploadBill> {

    private List<UploadBill> billList;
    private List<ExcelErrorParam> excelErrorMsgList;
    private Boolean isBlocked;

    public UploadBillReadListener(List<UploadBill> billList) {
        this.billList = billList;
        excelErrorMsgList = Lists.newArrayList();
        this.isBlocked = true;
    }

    public UploadBillReadListener(List<UploadBill> billList, boolean isBlocked) {
        this.billList = billList;
        excelErrorMsgList = Lists.newArrayList();
        this.isBlocked = isBlocked;
    }

    /**
     * 校验excel表头信息
     *
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        List<String> excelTitleList = Lists.newArrayList();
        // 获取excel的表头名称
        Field[] fields = UploadBill.class.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(ExcelProperty.class)) {
                ExcelProperty excelProperty = field.getDeclaredAnnotation(ExcelProperty.class);
                String[] valueArray = excelProperty.value();
                if (valueArray != null) {
                    excelTitleList.add(valueArray[0]);
                }
            }
        }
        // 校验excel表头
        headMap.forEach((index, readCellData) -> {
            if (!excelTitleList.contains(readCellData.getStringValue())) {
                log.error(">>>>> invokeHead：excel不存在【{}】表头字段信息", readCellData.getStringValue());
                throw new BusinessException(ResultRespEnum.UPLOAD_TEMPLATE_ERROR);
            }
        });
    }

    /**
     * 数据行校验
     *
     * @param uploadBill
     * @param context
     */
    @Override
    public void invoke(UploadBill uploadBill, AnalysisContext context) {
        Integer rowIndex = context.readRowHolder().getRowIndex();
        int rowNum = rowIndex + 1;
        ExcelErrorParam excelErrorParam = ValidateUtils.validateExcelData(rowNum, uploadBill);
        if (excelErrorParam != null) {
            excelErrorMsgList.add(excelErrorParam);
        } else {
            billList.add(uploadBill);
        }
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException ex = (ExcelDataConvertException) exception;
            String message = "第" + ex.getRowIndex() + "行，第" + ex.getColumnIndex() + "列数据解析异常，数据为" + ex.getCellData().getStringValue();
            throw new BusinessException(ResultRespEnum.UPLOAD_CONVERT_ERROR.getCode(), message);
        } else if (exception instanceof BusinessException) {
            BusinessException ex = (BusinessException) exception;
            throw new BusinessException(ex.getCode(), ex.getMessage(), ex.getData());
        } else {
            throw new BusinessException(ResultRespEnum.SYSTEM_ERROR.getCode(), exception.getMessage());
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info(">>>>>上传完毕...");
        // isBlocked=true表示数据校验失败，则返回异常信息
        if (isBlocked) {
            throw new BusinessException(ResultRespEnum.UPLOAD_VALIDATE_ERROR, excelErrorMsgList);
        }
    }
}
